checkLogin();

/*mui("#demo1").progressbar().show();*/
var login_value = getCache(login_key);
// var cartData = getCartList() || {};
var cartData = getCache('pay-order') || {};
$("#store_name").html(login_value.shop_name);
var num = Object.keys(cartData).length;
if (num <= 0) {
    malert('', '该数据已失效', '返回', function () {
        redirect('index.html')
    });
}
var html = template('goods_list_data', {data: cartData});
$("#goods_list").append(html);
var totalPrice = 0;
for (i in cartData) {
    totalPrice += cartData[i]['goods_num'] * cartData[i]['goods_price']
}
$("#totalPrice").html(totalPrice.toFixed(2));
$("#storeTotal").html(totalPrice.toFixed(2));
$("#order_amount").val(totalPrice.toFixed(2));


//获取地址列表
var success = function (res) {


    var info = res.data;

    //默认地址
    var html = template('address_data', info);
    var address = "";
    var addr = "";
    if (info.address_list != undefined && info.address_list != null && info.address_list != '' && info.address_list.length > 0) {
        for (var i = 0; i < info.address_list.length; i++) {
            if (info.address_list[i].is_default != undefined
                && info.address_list[i].is_default != null
                && info.address_list[i].is_default != ''
                && info.address_list[i].is_default == 1) {
                address = info.address_list[i];
                if (address == undefined || address == null || address == '') {
                    html = '<div class="no_address" style="padding: 0.5rem;font-size: 0.6rem;display: flex;display:-webkit-flex;' +
                        'align-items: center;-webkit-align-items:center;justify-content: space-between;-webkit-justify-content: space-between;">' +
                        '<div style="display: flex;display:-webkit-flex;align-items: center;-webkit-align-items: center"><img style="width: 1rem" src="image/add.png"><span style="margin-left: 0.5rem">' +
                        '暂无收货地址</span></div><img style="width: 0.6rem" src="image/right.png"></div>'
                }
                continue;
            }
        }
    } else {
        html = '<div class="no_address" style="padding: 0.5rem;font-size: 0.6rem;display: flex;display:-webkit-flex;' +
            'align-items: center;-webkit-align-items:center;justify-content: space-between;-webkit-justify-content: space-between;">' +
            '<div style="display: flex;display:-webkit-flex;align-items: center;-webkit-align-items: center"><img style="width: 1rem" src="image/add.png"><span style="margin-left: 0.5rem">' +
            '暂无收货地址</span></div><img style="width: 0.6rem" src="image/right.png"></div>'
        $("#ToBuyStep2").addClass('mui-disabled').attr('disabled', 'true');
    }

    $('#address_content').append(html);
    $('.no_address').on('tap', function () {
        var success = function (res) {
            var info = res.data.info;
            if (info == undefined || info == null || info == '') {
                malert('', '非法操作', function () {
                    checkLogin();
                });
            }
            // if (info.mobile == '' || info.mobile == undefined) {
            //     redirect("member-info.html?ref=1");
            // } else {
            //     redirect("add-address.html?ref=1");
            // }
            redirect("add-address.html?ref=1");
        }
        getData(member_info, comParams(), success);
    })

    //地址列表
    var html = template('address_list', info);
    $('#address_list_content').append(html);
    $('.choosed').addClass('none');
    if (info.address_list != undefined && info.address_list != null && info.address_list != '') {
        for (var i = 0; i < info.address_list.length; i++) {
            if (info.address_list[i].is_default != undefined
                && info.address_list[i].is_default != null
                && info.address_list[i].is_default != ''
                && info.address_list[i].is_default == 1) {
                $('.choosed' + info.address_list[i].id).removeClass('none');
            }
        }
    }
    //监听如果遮罩层打开，就关闭
    if (mui('.mui-off-canvas-wrap').offCanvas().isShown()) {
        mui('.mui-off-canvas-wrap').offCanvas().close();
    }

    //监听遮罩层的点击事件
    mui('.list_ocntent').on('tap', '.backdrop', function () {
        var sPrents = $(this).parents(".list_ocntent");
        var address_id = sPrents.attr('id');
        console.log(address_id)
        if (info.address_list != undefined && info.address_list != null && info.address_list != '') {
            for (var i = 0; i < info.address_list.length; i++) {
                info.address_list[i].is_default = 0;
                $('.choosed').addClass('none');
                if (info.address_list[i].id == address_id) {
                    address = info.address_list[i];
                    $('.choosed' + address_id).removeClass('none');
                    info.address_list[i].is_default = 1;
                    var address_detail = info.address_list[i];
                    $('.about-name-new').text(address_detail.name);
                    $('.about_mobile').text(address_detail.mobile);
                    var addr = address_detail.area_info + " " +address_detail.position_address+ address_detail.address;
                    $('#address_detail').text(addr);
                    $('#buyer_address').val(addr);
                    //设置默认地址
                    postData(address_set_default, combineParams
                    ({
                        id: address.id,
                        name: address.name,
                        mobile: address.mobile,
                        address: address.address,
                        area_info: address.area_info
                    }));
                    break;
                }
            }
        }
    });

    //显示或隐藏遮罩层
    $('.nctouch-cart-add-default').on('tap', function () {
        if (!mui('.mui-off-canvas-wrap').offCanvas().isShown()) {
            $('.mui-off-canvas-left').css('z-index', 2);
            mui('.mui-off-canvas-wrap').offCanvas().show();
            /*$('.zhezhao').removeClass('none');*/
        } else {
            mui('.mui-off-canvas-wrap').offCanvas().close();
            /*$('.zhezhao').addClass('none');*/
        }
    })

    $('.mui-off-canvas-right').on('tap', function () {
        mui('.mui-off-canvas-wrap').offCanvas().close();
        /*$('.zhezhao').addClass('none');*/
    })

    // 禁止冒泡，禁止跟手势滑动：
    document.getElementsByClassName('mui-inner-wrap')[0].addEventListener('drag', function (event) {
        event.stopPropagation();
    });
}

getData(address_list, comParams(), success);
var key_text = getCache(login_key);
var sid = key_text.sid;
var mid = key_text.mid;

var confirm_content = '首次订桶装水，无水桶需付桶押金，一次性桶装水无需押金，送水工线下收，可退';
var con_type = 1;
var alert_status = false;

//支付方式
var success = function (res) {
    var pay_type = res.data.pay_method;
    var html = template('pay_type_data', pay_type);
    $('.current-con').append(html);
    var url = '';
    if (pay_type.online_pay > 0) {
        url = order_pay;
    }
    if (pay_type.online_pay == 0 && pay_type.offline_pay > 0) {
        url = order_add;
    }

    //判断是否填写账户资料
    /*var mobile = getCache(login_key).mobile;
    if(isEmpty(mobile)){
        con_type = 0;
        setCache('confirm',true);
        confirm_content = '未绑定账户资料，立即去绑定';
        checkFrim();
    }else {*/
        con_type = 1;
        var order_success = getCache(mid + "_"+sid+'_'+'order');
        if(order_success == 1){
            setCache('confirm',false);
            checkBuyNum();
            /*checkFrim();*/
        } else {
            var success = function (res_new) {
                var list = res_new.data.order_list.data;
                var count = 0;
                setCache(mid + "_"+sid+'_'+'order',0);
                setCache('confirm',true);
                if(!isEmpty(list) && list.length > 0){
                    for(var i=0;i<list.length;i++){
                        if(list[i].status == 20){
                            count++;
                            break
                        }
                    }
                }
                if(count > 0){
                    setCache(mid + "_"+sid+'_'+'order',1);
                    setCache('confirm',false);
                }
                checkBuyNum();
                /*checkFrim();*/
            }
            getData(order_index,combineParams({type:1}),success);
        }
    /*}*/

    //判断是否超出购买限量
    function checkBuyNum() {
        alert_status = false;
        var success = function (res) {
            var info = res.data.buy_info;
            var max_num = 0;
            var min_num =0;
            var product_num = 0;
            var content = '';
            var shop_list = Object.keys(cartData);
            if(!isEmpty(shop_list) && shop_list.length>0){
                if (!isEmpty(login_value)){
                    //获取总的商品数量
                    for (var i=0;i<shop_list.length;i++){
                        var data = cartData[shop_list[i]];
                        product_num += data.goods_num;
                    }
                    max_num = info.buy_max;
                    min_num = info.buy_min;
                    if(max_num >0 && product_num > max_num){
                        //判断购买的商品数量是否超过最大购买数量
                        alert_status = true;
                        content = content + '最高购买数量为 '+ max_num +' 件';
                    }
                    if(min_num >= 1 && product_num < min_num){
                        alert_status = true;
                        content = content + '最低购买数量为 ' + min_num +' 件';
                    }
                }

                if(alert_status){
                    setCache('confirm',false);
                    confirm_content = content;
                }
                checkFrim();
            }
        }
        getData(buy_limit,comParams(),success);
    }

    function checkFrim() {
        var ajaxOption = {
            url: url,
            method: 'POST',
            alert: alert_status,
            alert_type:1,
            confirm: getCache('confirm'),
            confirm_title: '提示',
            confirm_content: confirm_content,//用[]包起来表示该值是函数，不包则为字符串
            data: combineParams({formId: 1}),
            success: function (res) {
                if (ajaxOption.url == order_add) {
                    clearCart();
                    locationReplace('success.html?type=1');
                } else {
                    payment(res.data);
                }
            },
            error: function (res) {
                return;
                if (con_type == 1) {
                    locationReplace('fail.html?type=1');
                } else {
                    redirect("member-info.html?ref=1");
                }
            }
        };
        if (pay_type.online_pay > 0 || pay_type.offline_pay > 0) {
            checkform($('#orderForm'), ajaxOption);
        } else {
            $("#ToBuyStep2").addClass('mui-disabled').attr('disabled', 'true');
        }

        /*$('.pay_type_wx').bind('click',function () {
         $("#native_pay").prop('checked', false);
         $("#wx_pay").prop('checked', true);
         ajaxOption.url = order_pay;
         });*/

        $('.pay_type_wx').on('tap', function () {
            $("#native_pay").prop('checked', false);
            $("#wx_pay").prop('checked', true);
            ajaxOption.url = order_pay;
        });

        $('.pay_type_na').on('tap', function () {
            $('#wx_pay').prop('checked', false);
            $('#native_pay').prop('checked', true);
            ajaxOption.url = order_add;
        });
    }

    check_button();


    //获取原始窗口的高度
    var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
    window.onresize = function () {
        //软键盘弹起与隐藏  都会引起窗口的高度发生变化
        var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
        if (resizeHeight * 1 < originalHeight * 1) { //resizeHeight<originalHeight证明窗口被挤压了
            $('.nctouch-cart-bottom').css('display', 'none');
            $('.remark-input').addClass('pos_fixed');
            $('.remark-input').removeClass('message');
            $('.bac_rgba').removeClass('none');

        } else {
            $('.remark-input').removeClass('pos_fixed');
            $('.remark-input').addClass('message');
            $('.bac_rgba').addClass('none');
            $('.nctouch-cart-bottom').css('display', 'block');
        }
    }

    $('.bac_rgba').on('tap', function () {
        $('.remark-input').removeClass('pos_fixed');
        $('.remark-input').addClass('message');
        $('.bac_rgba').addClass('none');
        $('.nctouch-cart-bottom').css('display', 'block');
        document.activeElement.blur();//关闭软键盘
    });

};
getData(pay_method, comParams(), success);

function check_button() {
    var _has = false
    $('.pay_type').each(function () {
        if ($(this).prop('checked')) {
            _has = true;
        }
    });
    if (_has) {
        $('.check-out').addClass('ok');
    } else {
        $('.check-out').removeClass('ok');
    }
}

//微信支付
function payment(data) {
    if (window.__wxjs_environment === 'miniprogram') {
        data.show_type = 1;
        var status = false;
        wx.miniProgram.redirectTo({
            url: '/pages/qds/wxpay/index?params=' + escape(JSON.stringify(data))
        })
        var mask = mui.createMask(function () {
            return false;
        });
        mask.show();//显示遮罩
        mui.confirm('', '是否支付成功 ?', ['是', '否'], function (e) {
            if (e.index == 0) {
                var success = function (res) {
                    if (res.data.result != undefined) {
                        status = res.data.result;
                    }
                    if (status) {
                        clearCart();
                        locationReplace('success.html?type=1');
                    } else {
                        locationReplace('fail.html?type=1');
                    }
                };
                getData(order_check_status, combineParams({id: data.id}), success);
            } else {
                locationReplace('fail.html?type=1');
            }
        })

    } else {
        wxPay(data, 1);
    }
}

//获取营业时间
var success = function (res) {
    var info = res.data.info;
    console.log(info)
    var html = template('time',info);
    $('#time_content').append(html);

}
getData(shop_info,comParams(),success);

//查询订单状态
// function queryOrderState(order_id,timestamp) {
//     console.log(order_id,timestamp);
//     $.ajax({
//         type: "GET",
//         url: order_check_status,
//         data: combineParams({id: order_id,m:Math.random()}),
//         dataType: "json",
//         timeout: 4000,
//         success: function (res) {
//             if (res.status == 1) {
//                 var status = false;
//                 if (res.data.result != undefined) {
//                     status = res.data.result;
//                 }
//                 if (status) {
//                     clearCart();
//                     redirect('success.html?type=1');
//                 }
//                 var now_timestamp = Date.parse( new Date());
//                 //超过1分钟订单状态还未支付，则弹出支付判定选项
//                 if (!status && now_timestamp - timestamp > 60000) {
//                     $(".mui-backdrop").remove();//移除提示遮罩
//                     var mask = mui.createMask(function(){return false;});
//                     mask.show();//显示选择遮罩
//                     mui.confirm('', '是否支付成功 ?', ['是', '否'], function (e) {
//                         if (e.index == 0) {
//                             var success = function (res) {
//                                 if (res.data.result != undefined) {
//                                     status = res.data.result;
//                                 }
//                                 clearCart();
//                                 if (status) {
//                                     redirect('success.html?type=1');
//                                 } else {
//                                     redirect('fail.html?type=1');
//                                 }
//                             };
//                             getData(order_check_status,combineParams({id:order_id}),success);
//                         } else {
//                             redirect('fail.html?type=1');
//                         }
//                     })
//                 }
//             } else {
//                 mui.alert(res.msg);
//             }
//         }
//     });
//     setTimeout("queryOrderState("+order_id+","+timestamp+")", 3000);
// }